

const { loginCheck } = require('../controller/user')
const { SuccessModel, ErrorModel } = require('../model/resModel')
const { set } = require('../db/redis')

// 设置cookie有效时间
const setCookieExpires = () => {
    const d = new Date()
    d.setTime(d.getTime() + (24 * 60 * 60 * 1000))
    return d.toGMTString()
}

setCookieExpires()

const handleUserRouter = (req, res) => {
    // const method = req.method  //获取请求方法
    // const url = req.url; //获取到资源路径  --/index.html?name=zhangsan
    // const path = url.split('?')[0]; //文件资源路径 --/index.html

    // 登录
    //  POST
    if (req.method === 'POST' && req.path === '/api/user/login') {
        // return {
        //     msg:'这是登录的数据接口'
        // }
        const { username, password } = req.body
        // const { username, password } = req.query
        const result = loginCheck(username, password)
        return result.then(data => {
            if (data.username) {
                // 操作cookie   path = /  有效路径
                res.setHeader('Set-Cookie', `username = ${data.username};path = /;HttpOnly`)
                req.session.username = data.username
                req.session.realname = data.realname

                // 同步到 redis 
                set(req.sessionId, req.session)
                return new SuccessModel('登陆成功')
            }
            return new ErrorModel('登陆失败')
        })
        /* if(result){
            return return new SuccessModel('登陆成功')
        }else{
            return new ErrorModel('登陆失败')
        }
         */
    }

    // 测试
    /* if (req.method === 'GET' && req.path === '/api/user/login-test') {
        /* const { username, password } = req.query
        const result = loginCheck(username, password)
        return result.then(data => {
            if (data.username) {
                // 操作cookie   path = /  有效路径
                res.setHeader('Set-Cookie', `username = ${data.username};path = /`)
                return new SuccessModel()
            }
            return new ErrorModel('还没有登录') */
        /* if (req.cookie.username) {
            return Promise.resolve(new SuccessModel({
                username: req.cookie.username
            })) */
        /*if (req.session.username) {
            return Promise.resolve(new SuccessModel({
                username: req.session.username
            }))
        }
        return Promise.resolve(new ErrorModel('还没有登录'))
    } */
    // if(req.cookie.username){

    // }
    // return Promise.resolve(new ErrorModel('还没有登录'))
}



module.exports = {
    
    handleUserRouter,
    setCookieExpires
} 







